﻿using SmartApi.Utils;
using SmartApi.Utils.Serialize;
using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace SmartApi
{

    public class PrepareRequest : IPrepareRequest
    {
        private readonly ISerialize _serialize;
        private readonly UrlPathParser _urlPathParser;

        public event OnPreparedHandler OnPrepared;

        public PrepareRequest(ISerialize serialize
            , UrlPathParser urlPathParser
            )
        {
            _serialize = serialize;
            _urlPathParser = urlPathParser;
        }
        public async Task Prepare(RequestContext requestContext)
        {
            Uri reqUri = PreRequestUri(requestContext);
            requestContext.HttpRequest = new HttpRequestMessage(requestContext.Method, reqUri);
            PreHeaders(requestContext);
            PreContent(requestContext);
            await OnPrepared?.Invoke(this, new OnPreparedEventArgs { RequestContext = requestContext });
        }

        protected Uri PreRequestUri(RequestContext requestContext)
        {
            var baseHost = new Uri(requestContext.Host);
            var urlPath = _urlPathParser.Parse(requestContext.UrlPath, requestContext.Parameters);
            return new Uri(baseHost, urlPath);
        }
        protected void PreHeaders(RequestContext requestContext)
        {
            if (requestContext.Headers != null)
            {
                foreach (var header in requestContext.Headers)
                {
                    requestContext.HttpRequest.Headers.Add(header.Key, header.Value);
                }
            }
        }
        protected void PreContent(RequestContext requestContext)
        {
            if (requestContext.Body != null)
            {
                var contentStr = _serialize.Serialize(requestContext.Body);
                requestContext.HttpRequest.Content = new StringContent(contentStr);
            }
        }
    }
}
